//
//  main.swift
//  FolderTraversal
//
//  Created by fcn on 2020/9/30.
//

import Foundation


class Folder: NSObject {
    var folderName = ""
    var subFolderArr: [Folder] = Array.init()
}
let manager = FileManager.default
let urlForDesktop = manager.urls(for: .desktopDirectory, in:.userDomainMask)[0] as URL
let urlForStep2 = urlForDesktop.appendingPathComponent("Step2")
print(urlForStep2)

func folderTraversal(_ url: URL) -> Folder {
    let folder = Folder.init()

    do {
        var paths = try manager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        folder.folderName = url.path
        
        paths = paths.sorted { (v1, v2) -> Bool in
            return v1.path.compare(v2.path) == .orderedAscending
        }
        
        for path in paths{
            var isDir: ObjCBool = ObjCBool(false) // 是否是文件夹
            manager.fileExists(atPath: path.path, isDirectory: &isDir)
            if isDir.boolValue {
                folder.subFolderArr.append(folderTraversal(path))
            }

//            print(path.path) // 路径名
        }
        
    } catch {
        print("")
    }
    
    return folder
}


var f = folderTraversal(urlForStep2)
//print(f.folderName)
printFolder(f, "--")

func printFolder(_ f: Folder, _ logo: String) {
    print("\(logo)\(f.folderName)")
    for subF in f.subFolderArr {
        printFolder(subF, logo + "--")
    }
}
